package com.zx.chatclient.fx.controller;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

import com.zx.chatclient.dto.IMUser;
import com.zx.chatclient.netty.Client;
import com.zx.chatclient.util.contants.ChatContants;

import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class FriendController implements ControlledStage, Initializable {

	private StageController myController;

	@FXML
	private AnchorPane userInfoPane;

	@FXML
	private AnchorPane friendPane;

	@FXML
	private Label unameLabel;

	@FXML
	private Label usexLabel;

	@FXML
	private Label uidLabel;

	@FXML
	private ListView<HBox> friendList;

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		IMUser user = Client.getUser();
		unameLabel.setText(user.getUname());
		uidLabel.setText(user.getUid());
		usexLabel.setText(user.getUsex());
		List<IMUser> friends = Client.getFriendList();
		for (IMUser imUser : friends) {
			HBox hBox = new HBox();
			Label uid = new Label();
			uid.setId("uid");
			uid.setText(imUser.getUid());
			Label uname = new Label();
			uname.setId("uname");
			uname.setText(imUser.getUname());
			hBox.getChildren().add(uid);
			hBox.getChildren().add(uname);
			hBox.setOnMouseClicked(new EventHandler<MouseEvent>() {
				@Override
				public void handle(MouseEvent event) {
					if (event.getClickCount() == 2) {
						HBox hBox = (HBox)event.getSource();
						List<Node> nodeList = hBox.getChildren();
						for (Node node : nodeList) {
							if ("uid".equals(node.getId())) {
								Label uid = (Label) node;
								uid.setText(uid.getText());
								myController.loadStage(uid.getText(), ChatContants.CHAT_VIEW_RES);
								Stage stage = myController.getStage(uid.getText());
								AnchorPane anchorPane = (AnchorPane) stage.getScene().getRoot();
								List<Node> chatNodes = anchorPane.getChildren();
								for (Node chatNode : chatNodes) {
									if ("senderLabel".equals(chatNode.getId())) {
										Label senderLabel = (Label) chatNode;
										senderLabel.setText(uid.getText());
									}
								}
								myController.setStage(uid.getText());
								break;
							}
						}
					}
				}
			});
			friendList.getItems().add(hBox);
		}
	}

	@Override
	public void setStageController(StageController stageController) {
		this.myController = stageController;
	}
}
